<?php

namespace App\Http\Controllers;

use App\Http\Requests\WithdrawController\WithdrawRequest;
use App\Http\Resources\ExportResource;
use App\Models\Account;
use App\Models\Address;
use App\Models\Coin;
use App\Models\User;
use App\Models\Withdraw;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Throwable;
use Overtrue\EasySms\PhoneNumber;
use Xrfg\Core\Trading\Account\Models\Account as TraddingAccount;

class WithdrawController extends Controller
{
    /**
     * 提现记录.
     *
     * @param Coin    $coin
     * @param Request $request
     *
     * @return \Illuminate\Http\Resources\Json\AnonymousResourceCollection
     */
    public function index(Coin $coin, Request $request)
    {
        $from = $request->query('from', 1);
        $perPage = $request->query('per_page', 15);
        $perPage = $perPage > 100 ? 100 : $perPage;

        $withdraws = Withdraw::where('user_id', Auth::id())
            ->when($coin->exists, function (Builder $query) use ($coin) {
                return $query->where('coin_id', $coin->id);
            })
            ->where('from', $from)
            ->orderByDesc('id')
            ->paginate($perPage);

        return ExportResource::collection($withdraws);
    }

    /**
     * 申请提现.
     *
     * @param WithdrawRequest $request
     *
     * @return \Illuminate\Http\Response
     *
     * @throws \Exception
     */
    public function store(WithdrawRequest $request)
    {
        //$this->error(20012);
        /** @var User $user */
        $user = Auth::user();
        $coinId = 1;
        $number = $request->input('number');
        $from = $request->input('from') == 2 ? 2 : 1; // 来源（1-以太星球 2-交易所）

        // 检查提币黑名单
        if (User::where('id', $user->id)->where('withdraw_switch', 1)->exists()) {
            $this->error(20007);
        }
        // 地址真实性验证
//        if (!Address::where('user_id', $user->id)->where('address', $request->input('address'))->exists()) {
//            $this->error(20008);
//        }

        $coin = Coin::where('id', $coinId)->first();
        if (1 !== $coin->can_withdraw) {
            $this->error(20003);
        }
        // 数量限制
        if ($number > $coin->withdraw_max) {
            $this->error(20004);
        }
        if ($number < $coin->withdraw_min) {
            $this->error(20005);
        }
        // 检查交易密码设置
        if (!$user->pay_password) {
            $this->error(20006);
        }
        // 检查实名认证状态
//        if (2 !== $user->kyc_status) {
//            $this->error(20007);
//        }

        // 获取提现账户
        if ($from == 1) { // 以太星球提现
            $account = Account::firstOrCreate([
                'user_id' => $user->id,
                'coin_id' => $coinId,
            ]);
            // 检查账户余额
            if (!isset($account->available) || $account->available < $number) {
                $this->error(20002);
            }
        } else { // 交易所提现
            $account = TraddingAccount::firstOrCreate([
                'user_id' => $user->id,
                'coin_id' => $coinId,
            ]);
            // 检查账户余额
            if (!isset($account->available) || $account->available < $number) {
                $this->error(20002);
            }
        }

        // 提现：提币手续费每笔固定3U
//        $withdraw_fee = 0.01;
//        $fee = bcmul($withdraw_fee, $number);
        $fee = 3;

        $withdraw = new Withdraw();
        $withdraw->user_id = $user->id;
        $withdraw->coin_id = $coinId;
        $withdraw->number = $number;
        $withdraw->fee = $fee;
        $withdraw->address = $request->input('address');
        $withdraw->note = $request->input('note');
        $withdraw->tag = $request->input('tag');
        $withdraw->from = $from;

        try {
            DB::transaction(function () use ($user, $number, $withdraw, $coinId, $from) {
                // 保存提现订单
                $withdraw->save();

                if ($from == 1) { // 以太星球提现
                    /** @var Account $account */
                    $account = Account::lockForUpdate()
                        ->where('user_id', $user->id)
                        ->where('coin_id', $coinId)
                        ->first();

                    $account->availableDecrement($number);
                    $account->disabledIncrement($number);
                    $account->type = '提现申请';
                    $account->action_id = $withdraw->id;
                    $account->save();
                } else { // 交易所提现
                    /** @var TraddingAccount $account */
                    $account = TraddingAccount::lockForUpdate()
                        ->where('user_id', $user->id)
                        ->where('coin_id', $coinId)
                        ->first();

                    $account->availableDecrement($number);
                    $account->disabledIncrement($number);
                    $account->proofId = [$withdraw->id, 2, 1];
                    $account->save();
                }

            });
        } catch (Throwable $exception) {
            Log::error($exception);
            $this->error();
        }

        return $this->null();
    }
}
